import {history} from 'umi'
let extraRoutes;

export function patchRoutes({ routes }) {
  // routes是当前已注册路由
  console.log(routes);
  // 动态添加路由
  routes.unshift({
    path: '/user/add',
    component: require('@/pages/User/UserAdd').default,
  });
  // 添加后的路由
  console.log(routes);

  // 添加动态请求的路由
  extraRoutes.map(item => {
    routes.unshift({
      path: item.path,
      component: require(`@/pages/User${item.component}`).default,
    })
  })
}

// 复写render在patchRoutes之前
export function render(oldRender) {
  // 动态请求路由
  // fetch('/api/routes').then(res=>res.json()).then((res) => { 
  //   extraRoutes = res.routes;
  //   oldRender();
  // })
  // 由于没有接口，暂时模拟请求回来的数据路由
  extraRoutes = [
    {path: '/serve', component: '/UserTwo'}
  ]

  // 渲染之前做权限校验
  const isLogin = true
  if (!isLogin) {
    history.push('/login')
  }

  // 渲染
  oldRender();
}

// 在初始加载和路由切换时做一些事情。在patchRoutes之后执行
export function onRouteChange({ location, routes, action, matchedRoutes }) {
  console.log(location, routes, action,'onRouteChange')
  // 用于埋点统计
  console.log(location.pathname)
  // 设置标题
  if (matchedRoutes.length) {
    document.title = '前缀名-' + (matchedRoutes[matchedRoutes.length - 1].route.title || '');
  }
}